<script setup>
import { ref } from 'vue'
import api from '@/api/request' // 确保导入你的 API 实例
import { ElMessage, ElDialog } from 'element-plus'
import {
  VideoCameraFilled,
  Camera,
  Upload,
  DataAnalysis
} from '@element-plus/icons-vue'

const video = ref(null)
const canvas = ref(null)
const selectedModel = ref('1')
const imageUrl = ref(null)
const previewImages = ref([])
const isCameraActive = ref(false)
const resultData = ref(null)
const isResultDialogVisible = ref(false)
const resultImageUrl = ref(null)
const fakeResponseData = {
  normal: 150, // 正常细胞数
  infected: 30, // 感染细胞数
  infection_rate: '20%', // 感染率
  bloodcell: 1 // 血细胞数
}

const captureImage = () => {
  const context = canvas.value.getContext('2d')
  context.drawImage(video.value, 0, 0, canvas.value.width, canvas.value.height)
  canvas.value.toBlob((blob) => {
    imageUrl.value = URL.createObjectURL(blob)
    previewImages.value = [imageUrl.value]
    stopCamera()
  }, 'image/png')
}

const showResultDialog = () => {
  if (
    resultData.value &&
    resultData.value.data &&
    resultData.value.data.imagebase64
  ) {
    resultImageUrl.value =
      'data:image/png;base64,' + resultData.value.data.imagebase64
    isResultDialogVisible.value = true
  } else {
    ElMessage.error('未返回有效的图片数据，请检查后端返回结果。')
  }
}

const uploadImage = async () => {
  if (!imageUrl.value) {
    ElMessage.error('没有可上传的图片')
    return
  }

  const response = await fetch(imageUrl.value)
  const blob = await response.blob()
  const formData = new FormData()
  formData.append('multipartFile', blob, 'capture.png')
  formData.append('selectmodelId', selectedModel.value)
  formData.append('modeltype', 'public')

  try {
    const response = await api.post('/photo', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })

    if (response.data.code === 200) {
      ElMessage.success('图片上传成功')
      resultData.value = response.data // 保存返回的数据
      console.log('resultData', resultData.value)
    } else {
      ElMessage.error('图片上传失败')
    }
  } catch (error) {
    console.error('请求失败:', error)
    ElMessage.error('请求失败')
  }
}

const requestCameraAccess = () => {
  navigator.mediaDevices
    .getUserMedia({ video: true })
    .then((stream) => {
      video.value.srcObject = stream
      isCameraActive.value = true
      ElMessage.success('摄像头已打开')
    })
    .catch((error) => {
      console.error('无法访问摄像头:', error)
      ElMessage.error('无法访问摄像头')
    })
}

const stopCamera = () => {
  if (video.value.srcObject) {
    const tracks = video.value.srcObject.getTracks()
    tracks.forEach((track) => track.stop())
    video.value.srcObject = null
    isCameraActive.value = false
    ElMessage.success('摄像头已关闭')
  }
}

const closeResultDialog = () => {
  isResultDialogVisible.value = false
}
</script>

<template>
  <div class="monitor-container">
    <div class="page-header">
      <h1>检测监控中心</h1>
      <p class="page-description">使用摄像头捕获细胞图像并进行分析</p>
    </div>

    <el-card class="video-card" shadow="hover">
      <div class="video-container">
        <video ref="video" autoplay playsinline></video>
        <canvas ref="canvas" style="display: none"></canvas>
      </div>

      <div class="model-selection">
        <el-select
          v-model="selectedModel"
          placeholder="选择检测模型"
          class="model-select"
        >
          <el-option label="细胞感染检测" value="1"></el-option>
          <el-option label="血细胞计数" value="2"></el-option>
        </el-select>
      </div>

      <div class="controls">
        <el-button
          type="primary"
          @click="requestCameraAccess"
          :disabled="isCameraActive"
          round
        >
          <el-icon><VideoCameraFilled /></el-icon> 打开摄像头
        </el-button>
        <el-button
          type="success"
          @click="captureImage"
          :disabled="!isCameraActive"
          round
        >
          <el-icon><Camera /></el-icon> 拍照
        </el-button>
        <el-button
          type="warning"
          @click="uploadImage"
          :disabled="!imageUrl"
          round
        >
          <el-icon><Upload /></el-icon> 上传分析
        </el-button>
        <el-button
          type="info"
          @click="showResultDialog"
          :disabled="!resultData"
          round
        >
          <el-icon><DataAnalysis /></el-icon> 查看结果
        </el-button>
      </div>
    </el-card>

    <el-card v-if="imageUrl" class="preview-card" shadow="hover">
      <template #header>
        <div class="card-header">
          <span>图像预览</span>
        </div>
      </template>
      <el-image
        :src="imageUrl"
        alt="预览图片"
        class="preview-image"
        :preview-src-list="previewImages"
        fit="cover"
      />
    </el-card>

    <el-dialog
      v-model="isResultDialogVisible"
      title="检测结果分析"
      width="60%"
      destroy-on-close
      center
      class="result-dialog"
    >
      <div class="result-content">
        <img :src="resultImageUrl" alt="检测结果图片" class="result-image" />
        <div class="result-data">
          <el-descriptions title="分析数据" :column="1" border>
            <template v-if="resultData && selectedModel === '1'">
              <el-descriptions-item label="正常细胞数">{{
                fakeResponseData.normal
              }}</el-descriptions-item>
              <el-descriptions-item label="感染细胞数">{{
                fakeResponseData.infected
              }}</el-descriptions-item>
              <el-descriptions-item label="感染率">{{
                fakeResponseData.infection_rate
              }}</el-descriptions-item>
            </template>
            <template v-else-if="resultData && selectedModel === '2'">
              <el-descriptions-item label="血细胞数">{{
                fakeResponseData.bloodcell
              }}</el-descriptions-item>
            </template>
          </el-descriptions>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="closeResultDialog">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.monitor-container {
  padding: 32px;
  background: #ffffff;
  min-height: calc(100vh - 60px);
  border-radius: 16px;
  box-shadow: 0 4px 24px rgba(115, 103, 240, 0.08);
}

.page-header {
  margin-bottom: 40px;

  h1 {
    font-size: 24px;
    font-weight: 600;
    color: #1e1e2d;
    margin: 0 0 16px 0;
    position: relative;

    &::after {
      content: '';
      position: absolute;
      bottom: -8px;
      left: 0;
      width: 40%;
      height: 2px;
      background: linear-gradient(90deg, #7367f0 0%, transparent 100%);
    }
  }

  .page-description {
    color: #6e6b7b;
    font-size: 16px;
    margin: 0;
  }
}

.video-card {
  border-radius: 16px;
  overflow: hidden;
  box-shadow: 0 4px 24px rgba(115, 103, 240, 0.08);
  transition: all 0.3s;
  background: white;
  margin-bottom: 40px;
  padding: 32px;

  &:hover {
    box-shadow: 0 8px 32px rgba(115, 103, 240, 0.12);
    transform: translateY(-4px);
  }
}

.video-container {
  position: relative;
  margin-bottom: 36px;

  video {
    width: 100%;
    max-width: 100%;
    border-radius: 16px;
    height: 480px;
    object-fit: cover;
    background-color: #1e1e2d;
    box-shadow: 0 4px 24px rgba(30, 30, 45, 0.15);
  }
}

.model-selection {
  margin-bottom: 36px;

  .model-select {
    width: 100%;
    max-width: 320px;

    :deep(.el-input__wrapper) {
      padding: 4px 16px;
      border-radius: 12px;
      box-shadow: 0 4px 12px rgba(115, 103, 240, 0.1);
      transition: all 0.3s ease;

      &:hover {
        box-shadow: 0 6px 16px rgba(115, 103, 240, 0.15);
      }

      &.is-focus {
        box-shadow: 0 0 0 2px rgba(115, 103, 240, 0.2);
      }
    }

    :deep(.el-input__inner) {
      height: 46px;
      font-size: 16px;
      color: #1e1e2d;
    }
  }
}

.controls {
  display: flex;
  flex-wrap: wrap;
  gap: 20px;
  margin-bottom: 20px;

  .el-button {
    padding: 12px 24px;
    font-size: 16px;
    border-radius: 12px;
    transition: all 0.3s;

    &:hover:not(:disabled) {
      transform: translateY(-4px);
      box-shadow: 0 8px 20px rgba(115, 103, 240, 0.2);
    }

    &.is-disabled {
      opacity: 0.7;
      cursor: not-allowed;
    }

    .el-icon {
      margin-right: 10px;
      font-size: 20px;
    }

    &--primary {
      background: linear-gradient(135deg, #7367f0 0%, #9f94ff 100%);
      border: none;
    }

    &--success {
      background: linear-gradient(135deg, #28c76f 0%, #48da89 100%);
      border: none;
    }

    &--warning {
      background: linear-gradient(135deg, #ff9f43 0%, #ffb976 100%);
      border: none;
    }

    &--info {
      background: linear-gradient(135deg, #00cfe8 0%, #1ce7ff 100%);
      border: none;
    }
  }
}

.preview-card {
  border-radius: 16px;
  overflow: hidden;
  box-shadow: 0 4px 24px rgba(115, 103, 240, 0.08);
  transition: all 0.3s;
  margin-bottom: 40px;
  padding: 0;

  &:hover {
    box-shadow: 0 8px 32px rgba(115, 103, 240, 0.12);
    transform: translateY(-4px);
  }

  .card-header {
    font-weight: 600;
    font-size: 18px;
    padding: 20px 24px;
    border-bottom: 1px solid rgba(115, 103, 240, 0.1);
    color: #1e1e2d;
    background: linear-gradient(to right, #f8f8fb, #ffffff);
  }

  .preview-image {
    width: 100%;
    height: 480px;
    border-radius: 0;
    cursor: pointer;
    transition: all 0.3s ease;

    &:hover {
      transform: scale(1.02);
    }
  }
}

.result-dialog {
  :deep(.el-dialog) {
    border-radius: 16px;
    overflow: hidden;
    box-shadow: 0 4px 32px rgba(115, 103, 240, 0.15);

    .el-dialog__header {
      padding: 24px;
      margin: 0;
      border-bottom: 1px solid rgba(115, 103, 240, 0.1);
      text-align: center;
      background: linear-gradient(to right, #f8f8fb, #ffffff);

      .el-dialog__title {
        font-size: 20px;
        font-weight: 600;
        color: #1e1e2d;
      }
    }

    .el-dialog__body {
      padding: 32px;
    }

    .el-dialog__footer {
      border-top: 1px solid rgba(115, 103, 240, 0.1);
      padding: 24px;
      background: linear-gradient(to right, #f8f8fb, #ffffff);
    }
  }

  .result-content {
    display: flex;
    flex-direction: column;
    gap: 36px;

    @media (min-width: 768px) {
      flex-direction: row;
    }
  }

  .result-image {
    width: 100%;
    max-width: 550px;
    border-radius: 16px;
    margin: 0 auto;
    box-shadow: 0 4px 24px rgba(115, 103, 240, 0.08);
    transition: all 0.3s ease;

    &:hover {
      transform: translateY(-4px);
      box-shadow: 0 8px 32px rgba(115, 103, 240, 0.15);
    }
  }

  .result-data {
    flex: 1;
    min-width: 300px;

    :deep(.el-descriptions) {
      .el-descriptions__header {
        margin-bottom: 24px;

        .el-descriptions__title {
          font-size: 20px;
          font-weight: 600;
          color: #1e1e2d;
          position: relative;

          &::after {
            content: '';
            position: absolute;
            bottom: -8px;
            left: 0;
            width: 40%;
            height: 2px;
            background: linear-gradient(90deg, #7367f0 0%, transparent 100%);
          }
        }
      }

      .el-descriptions__body {
        background-color: #f8f8fb;
        border-radius: 12px;
        overflow: hidden;
        box-shadow: 0 4px 24px rgba(115, 103, 240, 0.08);

        .el-descriptions__label {
          padding: 16px 24px;
          font-weight: 500;
          font-size: 16px;
          color: #6e6b7b;
          background: linear-gradient(to right, #f8f8fb, #ffffff);
        }

        .el-descriptions__content {
          padding: 16px 24px;
          font-size: 16px;
          color: #1e1e2d;
        }

        .el-descriptions__cell {
          border-color: rgba(115, 103, 240, 0.1);
        }
      }
    }
  }

  .dialog-footer {
    .el-button {
      padding: 12px 28px;
      font-size: 16px;
      border-radius: 12px;
      transition: all 0.3s ease;

      &--primary {
        background: linear-gradient(135deg, #7367f0 0%, #9f94ff 100%);
        border: none;

        &:hover {
          transform: translateY(-3px);
          box-shadow: 0 8px 24px rgba(115, 103, 240, 0.2);
        }
      }
    }
  }
}
</style>
